package com.hlk.article.controller;

import com.hlk.config.RabbitmqConfig;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageDeliveryMode;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

/**
 * @author hlk
 * @version 1.0
 * @date 2020-12-15 15:43
 */
@RestController
@RequestMapping("hello")
public class HellowController {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @GetMapping("hello")
    public String hello() {
        rabbitTemplate.convertAndSend(RabbitmqConfig.EXCHANGE_ARTICLE, "article.html", "这是生产者发的消息");
        return "Hello";
    }

    @GetMapping("/delay")
    public Object delay() {

        MessagePostProcessor messagePostProcessor = new MessagePostProcessor() {
            @Override
            public Message postProcessMessage(Message message) throws AmqpException {
                // 设置消息的持久
                message.getMessageProperties()
                        .setDeliveryMode(MessageDeliveryMode.PERSISTENT);
                // 设置消息延迟的时间，单位ms毫秒
                message.getMessageProperties()
                        .setDelay(5000);
                return message;
            }
        };

        rabbitTemplate.convertAndSend(
                RabbitmqConfig.EXCHANGE_DELAY,
                "publish.delay.demo",
                "这是一条延迟消息~~",
                messagePostProcessor);

        System.out.println("生产者发送的延迟消息：" + new Date());

        return "OK";
    }

}
